package controller

import (
	"admin/contrib/session"
	"admin/model"
	"common/helper"
	"encoding/json"
	"github.com/valyala/fasthttp"
	"strconv"
	"strings"
	"time"
)

type BusinessController struct{}

type BusinessParam struct {
	Id        string `json:"id"`
	ProxyType string `json:"type"`
	ParentId  string `json:"parent_id"`
	Page      int    `json:"page"`
	PageSize  int    `json:"page_size"`
}

// ConfigList 代理渠道配置列表
func (that BusinessController) BusinessList(ctx *fasthttp.RequestCtx) {
	param := BusinessParam{}

	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}

	if param.Page < 1 {
		param.Page = 1
	}
	if param.PageSize < 10 || param.PageSize > 10000 {
		helper.RetData(ctx, false, "参数错误")
		return
	}
	s, err := model.BusinessList(param.Page, param.PageSize, param.Id, param.ParentId, param.ProxyType, ctx)
	//获取三方游戏列表
	platform, err := model.GetPlatformByPid("0")

	platformList := map[string]model.Platform{}
	for _, value := range platform {
		platformList[value.ID] = value
	}
	//loginUser := model.GetLoginUser(ctx)
	for key, value := range s.D {
		apiFeeRate := map[string]float64{}
		json.Unmarshal([]byte(value.ApiFee), &apiFeeRate)

		newApiFee := []model.ApiFee{}
		for _, v := range platform {
			newApiFee = append(newApiFee, model.ApiFee{
				GameId:   v.ID,
				GameName: v.Name,
				Rate:     apiFeeRate[v.ID],
			})
		}
		jsonBytes, _ := json.Marshal(newApiFee)
		(s.D)[key].ApiFee = string(jsonBytes)
		(s.D)[key].Seamo = ""
		//if loginUser.Businsess != "" {
		//(s.D)[key].Password = ""
		//}
	}
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, s)
}

// ConfigInsert 业务员新增
func (that *BusinessController) BusinessInsert(ctx *fasthttp.RequestCtx) {

	param := model.TblBusinessInfo{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}

	admin := session.AdminGet(ctx)
	if admin["loginuser"] == "merchant" {
		param.OperatorId = admin["id"]
		if param.ParentId == "" {
			param.ParentId = "0"
			param.ParentName = ""
		} else {
			businessInfo, _ := model.GetBusinessInfoById(param.ParentId)
			param.ParentId = param.ParentId
			param.ParentName = businessInfo.LoginAccount
		}
	} else if admin["loginuser"] == "business" {
		businessInfo, _ := model.GetBusinessInfoById(admin["id"])
		param.OperatorId = businessInfo.OperatorId
		param.ParentId = admin["id"]
		param.ParentName = admin["name"]
		param.Type = "普通业务员"
	}
	has, _ := model.GetBusinessInfoByLoginAccount(param.LoginAccount)
	if has.Id != "" {
		helper.RetData(ctx, false, "用户已存在")
		return
	}
	if param.Password == "" || param.AccountName == "" || param.LoginAccount == "" {
		helper.RetData(ctx, false, "名称，账号或密码 不能为空")
		return
	}
	//api费用
	if param.ApiFee == "" {
		//使用渠道的
		operator, _ := model.GetOperatorInfoById(param.OperatorId)
		param.ApiFee = operator.ApiFee
		param.WithdrawFee = operator.WithdrawFee
		param.RechargeFee = operator.RechargeFee
	} else {
		platform, _ := model.GetPlatformByPid("0")
		AddApiFee := strings.Split(param.ApiFee, ",")
		newFeeRate := map[string]float64{}
		for k, v := range platform {
			if len(AddApiFee) < k+1 {
				newFeeRate[v.ID] = 0
			} else {
				floatFee, _ := strconv.ParseFloat(AddApiFee[k], 64)
				newFeeRate[v.ID] = floatFee
			}

		}
		jsonBytes, _ := json.Marshal(newFeeRate)
		param.ApiFee = string(jsonBytes)
	}
	if model.ValidatePassword(param.Password) == false {
		helper.RetData(ctx, false, "业务员密码至少8位数，大、小写英文字母+数字组合")
		return
	}
	err = model.BusinessInsert(param)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	model.SynRedis(ctx)
	model.GameFlushAll()
	helper.RetData(ctx, true, "succeed")
}

// ConfigUpdate 业务员更新
func (that BusinessController) BusinessUpdate(ctx *fasthttp.RequestCtx) {

	param := model.TblBusinessInfo{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	has, _ := model.GetBusinessInfoByLoginAccount(param.LoginAccount)

	if has.Id != "" && has.Id != param.Id {
		helper.RetData(ctx, false, "用户已存在")
		return
	}

	admin := session.AdminGet(ctx)
	if admin["loginuser"] == "merchant" {

	} else if admin["loginuser"] == "business" {
		param.Type = "普通业务员"
	}
	err = model.BusinessUpdate(param)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	model.SynRedis(ctx)
	model.GameFlushAll()
	helper.RetData(ctx, true, "成功")
}

// 渠道api费用
func (that *BusinessController) ApifeeUpdate(ctx *fasthttp.RequestCtx) {
	param := model.TblBusinessInfo{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	model.InsertLog("业务员api费用编辑", ctx)
	admin := session.AdminGet(ctx)
	if admin["loginuser"] != "merchant" {
		helper.RetData(ctx, false, "权限不足")
		return
	}
	business, _ := model.GetBusinessInfoById(param.Id)
	if business.OperatorId != admin["id"] {
		helper.RetData(ctx, false, "权限不足")
		return
	}
	operator, _ := model.GetOperatorInfoById(admin["id"])
	//fmt.Println(operator)
	if operator.WithdrawFee > param.WithdrawFee {
		helper.RetData(ctx, false, "提现手续费不得低于渠道本身的点位")
		return
	}
	if operator.RechargeFee > param.RechargeFee {
		helper.RetData(ctx, false, "充值手续费不得低于渠道本身的点位")
		return
	}
	//newFeeRate2 := []model.ApiFee{}
	apiFeeRate2 := map[string]float64{}
	json.Unmarshal([]byte(operator.ApiFee), &apiFeeRate2)

	newFeeRate := []model.ApiFee{}
	json.Unmarshal([]byte(param.ApiFee), &newFeeRate)
	apiFeeRate := map[string]float64{}

	for _, v := range newFeeRate {
		if apiFeeRate2[v.GameId] > v.Rate {
			helper.RetData(ctx, false, "API手续费不得低于渠道本身的点位")
			return
		}
		apiFeeRate[v.GameId] = v.Rate

	}
	jsonBytes, _ := json.Marshal(apiFeeRate)
	param.ApiFee = string(jsonBytes)
	err = model.BusinessApifeeUpdate(admin["name"], admin["id"], param)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}

func (that *BusinessController) ToBusiness(ctx *fasthttp.RequestCtx) {
	param := model.TblBusinessInfo{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}
	if param.Id == "" {
		helper.RetData(ctx, false, "参数错误")
		return
	}
	admin := session.AdminGet(ctx)
	if admin["loginuser"] != "merchant" {
		helper.RetData(ctx, false, "权限不足")
		return
	}
	business, err := model.GetBusinessInfoById(param.Id)
	if business.OperatorId != admin["id"] {
		helper.RetData(ctx, false, "权限不足")
		return
	}
	token, err := session.AdminSet("business", business.Id, business.LoginAccount, business.Password)

	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	rsp := model.BusinessLoginResp{
		Token:        token,
		LoginAccount: business.LoginAccount,
		Id:           business.Id,
		Date:         time.Now().Unix(),
		OperatorId:   business.OperatorId,
		Seamo:        "",
		CodeUrl:      "",
	}
	helper.RetData(ctx, true, rsp)
}

func (that *BusinessController) BusinessToken(ctx *fasthttp.RequestCtx) {

	admin := session.AdminGet(ctx)
	if admin["loginuser"] != "business" {
		helper.RetData(ctx, false, "权限不足")
		return
	}
	business, _ := model.GetBusinessInfoById(admin["id"])
	if business.Id == "" {
		helper.RetData(ctx, false, "权限不足")
	}
	//清除token
	session.AdminClear(ctx)

	//构造token
	token, err := session.AdminSet("business", business.Id, business.LoginAccount, business.Password)

	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	rsp := model.BusinessLoginResp{
		Token:        token,
		LoginAccount: business.LoginAccount,
		Id:           business.Id,
		Date:         time.Now().Unix(),
		OperatorId:   business.OperatorId,
		Seamo:        "",
		CodeUrl:      "",
	}
	helper.RetData(ctx, true, rsp)
}

func (that *BusinessController) ChangeAllPassword(ctx *fasthttp.RequestCtx) {

	admin := session.AdminGet(ctx)
	if admin["loginuser"] != "merchant" {
		helper.RetData(ctx, false, "权限不足")
		return
	}

	param := model.TblBusinessInfo{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}

	err = model.UpdateBusinessPassword("", param.Password, admin["id"])
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}
	helper.RetData(ctx, true, "成功")
}
